<script setup>
import { ref, onMounted } from 'vue'
import { useCounterStore } from '@/stores/counter'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const { editGoods, getGoodsById } = useCounterStore()

const name = ref('')
const price = ref('')
const id = route.params.id

const handleEditGoods = () => {
  //判断
  if (!name.value || !price.value) {
    alert('请输入有效信息！')
    return
  }

  //修改
  editGoods(id, name.value, price.value)

  //跳转
  router.push('/home/manage')
}

const handleEditCancel = () => {
  router.push('/home/manage')
}

onMounted(async () => {
  const res = await getGoodsById(id)
  name.value = res.name
  price.value = res.price
})
</script>

<template>
  <div>
    <h2>修改商品</h2>
    名称：<input type="text" v-model="name" />
    <br />
    价格：<input type="text" v-model.number.trim="price" />
    <br />
    <button @click="handleEditGoods" class="edit">修改</button>
    <button @click="handleEditCancel" class="cancel">取消</button>
  </div>
</template>

<style scoped>
h2 {
  margin-left: 80px;
  margin-bottom: 10px;
}

input {
  padding: 5px;
}
input:nth-of-type(2) {
  margin-top: 5px;
}

button {
  border: none;
  border-radius: 3px;
  padding: 5px 15px;
  color: white;
}

.edit {
  margin: 5px 0 0 50px;
  background: #0099ff;
}
.cancel {
  margin: 5px;
  background: orange;
}
</style>
